package com.szpx.service.impl;

import com.szpx.entity.XWY.XWYDenglu;
import com.szpx.mapper.XWYDengluMapper;
import com.szpx.service.XWYDengluService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

/**
 * XWY登录服务实现类
 */
@Service
public class XWYDengluServiceImpl implements XWYDengluService {

    @Autowired
    private XWYDengluMapper xwyDengluMapper;

    @Override
    public XWYDenglu selectByPhone(String phone) {
        return xwyDengluMapper.selectByPhone(phone);
    }

    @Override
    public XWYDenglu selectByUsername(String username) {
        return xwyDengluMapper.selectByUsername(username);
    }

    @Override
    public List<XWYDenglu> selectAlldenglu() {
        return xwyDengluMapper.selectAlldenglu();
    }

    @Override
    public XWYDenglu login(String account, String password) {
        // 先尝试用手机号登录
        XWYDenglu user = selectByPhone(account);
        if (user == null) {
            // 如果手机号登录失败，尝试用用户名登录
            user = selectByUsername(account);
        }
        
        // 对输入的密码进行MD5加密
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        
        // 验证密码
        if (user != null && user.getPassword().equals(md5Password)) {
            return user;
        }
        
        return null;
    }

    @Override
    public XWYDenglu loginWithRole(String phone, String password, String role) {
        XWYDenglu user = selectByPhone(phone);
        
        // 对输入的密码进行MD5加密
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        
        // 验证密码和角色
        if (user != null && user.getPassword().equals(md5Password) && role.equals(user.getRole())) {
            return user;
        }
        
        return null;
    }

    @Override
    public int register(XWYDenglu user) {
        // 检查用户名和手机号是否已存在
        if (selectByUsername(user.getUsername()) != null || 
            selectByPhone(user.getPhone()) != null) {
            return 0;
        }
        
        return xwyDengluMapper.insert(user);
    }

    @Override
    public boolean checkUsername(String username) {
        return selectByUsername(username) != null;
    }
    
    @Override
    public boolean checkPhone(String phone) {
        return selectByPhone(phone) != null;
    }
}